import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  // history: createWebHashHistory(),
  routes: [
    {
      path: '/play',
      component: () => import('@/views/playground/index.vue'),
      meta: {
        title: '演示'
      }
    },
    {
      path: '/login',
      component: () => import('@/views/login/index.vue'),
      meta: {
        title: '登录'
      }
    },
    {
      path: '/',
      component: () => import('@/views/layout/index.vue'),
      redirect: '/home',
      children: [
        {
          path: '/home',
          component: () => import('@/views/home/index.vue'),
          meta: {
            title: '首页'
          }
        },
        {
          path: '/article',
          component: () => import('@/views/article/index.vue'),
          meta: {
            title: '健康百科'
          }
        },
        {
          path: '/notify',
          component: () => import('@/views/notify/index.vue'),
          meta: {
            title: '消息中心'
          }
        },
        {
          path: '/user',
          component: () => import('@/views/user/index.vue'),
          meta: {
            title: '我的'
          }
        }
      ]
    },
    {
      path: '/user/patient',
      component: () => import('@/views/user/patient-page.vue'),
      meta: { title: '家庭档案' }
    },
    {
      path: '/consult/fast',
      component: () => import('@/views/consult/consult-fast.vue'),
      meta: { title: '极速问诊' }
    },
    {
      path: '/consult/dep',
      component: () => import('@/views/consult/consult-dep.vue'),
      meta: { title: '极速问诊' }
    }
  ]
})

// 导航守卫
/*
   全局
      beforeEach
      afterEach
      beforeResolve
   配制
      beforeEnter
   组件
      beforeRouteEnter
      beforeRouteUpdate
      beforeRouteLeave

*/
// 如果参数有next===>next():放行  next('/login') 跳转到登录页
// 如果无参数next   没有return处理就是放行  return '/login' 跳转到登录页

import { useUserStore } from '@/stores'
// 白名单
const whiteList = ['/login']

// 进度条插件  nprogress
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false })
router.beforeEach(to => {
  NProgress.start()
  // return '/login'  ====> next('/login')
  // 没有登录（token），且不在白名单页面的就跳转到登录页
  const store = useUserStore()
  const token = store.userInfo?.token
  if (!token && !whiteList.includes(to.path.toLowerCase())) {
    return '/login?redirect=' + to.fullPath
  }
})

router.afterEach(to => {
  NProgress.done()
  console.log('to', to)
  // document.querySelector('title')!.innerText = '优医问诊-' + to.meta.title
  document.title = '优医问诊-' + to.meta.title
})
export default router
